<template>
  <div class="login">
    <van-nav-bar
      title="登录"
      left-arrow
      @click-left="onClickLeft"
      class="page-navbar"
    />
    <van-form
      validate-first
      :show-error='false'
      :show-error-message='false'
      ref='login-form'
      @submit="onLogin"
      @failed="onFailed"
    >
      <van-field
        v-model="user.mobile"
        icon-prefix="toutiao"
        left-icon="shouji"
        placeholder="请输入手机号"
        name="mobile"
        center
        :rules='formRules.mobile'
      />
      <van-field
        v-model="user.code"
        icon-prefix="toutiao"
        left-icon="yanzhengma"
        placeholder="验证码"
        name="code"
        center
        :rules='formRules.code'
      >
        <template #button>
          <van-count-down
            :time="1000 * 60"
            format="ss 秒"
            v-if="isCountdownShow"
            @finish='isCountdownShow=false'
          />
          <van-button
            size="small"
            type="primary"
            @click.prevent='onSendsms'
            :loading='isSendSmsLoading'
            loading-text='加载中'
            v-else
          >获取验证码</van-button>
        </template>
      </van-field>
      <div class="login-btn-wrap">
        <van-button
          class="login-btn"
          type="info"
          block
        >登录</van-button>
      </div>
    </van-form>
  </div>
</template>
<script>
import { login, sendSms } from '@/api/user'
export default {
  data: () => ({
    user: {
      mobile: '13911111111', // 手机号
      code: '246810' // 验证码
    },
    formRules: {
      mobile: [
        { required: true, message: '请输入手机号' },
        { pattern: /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/, message: '手机号格式错误' }
      ],
      code: [
        { required: true, message: '请输入验证码' },
        { pattern: /^\d{6}$/, message: '验证码格式错误' }
      ]
    },
    isCountdownShow: false,
    isSendSmsLoading: false
  }),
  methods: {
    onClickLeft() {
      this.$router.go(-1)
    },
    async onLogin() {
      this.$toast.loading({
        duration: 0, // 持续时间，0表示持续展示不停止
        forbidClick: true, // 是否禁止背景点击
        message: '登录中...' // 提示消息
      })
      try {
        const { data } = await login(this.user)

        this.$toast.success('登录成功')
        this.$store.commit('loginStore/setUser', data.data)

        // const redirect = this.$route.query.redirect || '/'
        this.$router.back()
      } catch (err) {
        console.log(err)
        this.$toast.fail('登录失败, 手机号或验证码错误')
      }
    },
    onFailed(err) {
      this.$toast({
        message: err.errors[0].message,
        position: 'top'
      })
    },
    async onSendsms() {
      try {
        await this.$refs['login-form'].validate('mobile')
        this.isSendSmsLoading = true

        await sendSms(this.user.mobile)
        this.isCountdownShow = true
      } catch (err) {
        let message = ''
        if (err && err.response && err.response.status === 429) {
          message = '发送太频繁了,请稍后再试'
        } else if (err.name === 'mobile') {
          message = err.message
        } else {
          message = '发送失败，请稍后重试'
        }
        this.$toast({
          message,
          position: 'top'
        })

        this.isCountdownShow = false
        this.isSendSmsLoading = false
      }
    }
  }
}
</script>
<style lang="less">
.login {
  .send-btn {
    width: 76px;
    height: 23px;
    background-color: #ededed;
    .van-button__text {
      font-size: 11px;
      color: #666666;
    }
  }
  .login-btn-wrap {
    padding: 26px 16px;
    .login-btn {
      background-color: #6db4fb;
      border: none;
      .van-button__text {
        font-size: 15px;
      }
    }
  }
}
</style>